package com.shundr.frame.service;

import java.util.ArrayList;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.shundr.common.util.PrefConstants;
import com.shundr.common.util.PrefUtils;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.util.LLogger;
import com.shundr.frame.util.StringUtil;

/**
 * 电话监听
 * PhoneReceiver
 * 
 * @author larry 2015-5-20 下午6:18:25 
 * @version 1.0.0
 *
 */
public class PhoneReceiver extends BroadcastReceiver {
 
	public static ArrayList<PhoneHandler> mPhoneListeners = new ArrayList<PhoneHandler>();
	public static ArrayList<SmsHandler> mSmsListeners = new ArrayList<SmsHandler>();
	
	private final String ACTION_SMS = "android.provider.Telephony.SMS_RECEIVED";
	
	protected Context context;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context=context;
		System.out.println("action" + intent.getAction());
		LLogger.e("我接收到短信啦");
		// 如果是去电
		if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
			String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
			LLogger.e("call OUT:" + phoneNumber);
			//关闭语音播报
			boolean isOpen = PrefUtils.getPrefBoolean(context, PrefConstants.IS_TTS_ON, true);
			if(isOpen){
				LContext.mTtsTools.stop();
				LContext.isTtsOpened = false;
			}
		} else if (intent.getAction().equals(ACTION_SMS)) {//接收到短信
			OnSmsReceived(intent);
		} else {
			// 查了下android文档，貌似没有专门用于接收来电的action,所以，非去电即来电.
			/**
			 * 如果我们想要监听电话的拨打状况，需要这么几步 : 第一：获取电话服务管理器TelephonyManager manager =
			 * this.getSystemService(TELEPHONY_SERVICE);
			 * 第二：通过TelephonyManager注册我们要监听的电话状态改变事件。manager.listen(new
			 * MyPhoneStateListener(),
			 * PhoneStateListener.LISTEN_CALL_STATE);这里的PhoneStateListener
			 * .LISTEN_CALL_STATE就是我们想要 监听的状态改变事件，初次之外，还有很多其他事件哦。 第三步：通过extends
			 * PhoneStateListener来定制自己的规则。将其对象传递给第二步作为参数。
			 * 第四步：这一步很重要，那就是给应用添加权限。android.permission.READ_PHONE_STATE
			 */

			TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
			tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
			LContext.getTtsTools(context);
			// 设置一个监听器
		}
	}

	PhoneStateListener listener = new PhoneStateListener() {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// 注意，方法必须写在super方法后面，否则incomingNumber无法获取到值。
			super.onCallStateChanged(state, incomingNumber);
			boolean isOpen = PrefUtils.getPrefBoolean(context, PrefConstants.IS_TTS_ON, true);
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE://挂断
				if(isOpen){
					LContext.isTtsOpened = true;
				}
				LLogger.e("TelephonyManager.CALL_STATE_IDLE");
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK://接听
				if(isOpen){
					LContext.isTtsOpened = false;
					LContext.mTtsTools.stop();
				}
				LLogger.e("接听电话了");
				break;
			case TelephonyManager.CALL_STATE_RINGING://来电未接听
				System.out.println("响铃:来电号码" + incomingNumber);
				if(isOpen){
					LContext.mTtsTools.stop();
					LContext.isTtsOpened = false;
				}
				break;
			}
		}
	};
	
	private void OnSmsReceived(Intent intent){
		Object[] objs = (Object[]) intent.getExtras().get("pdus");
		for (Object obj : objs) {
			byte[] pdu = (byte[]) obj;
			SmsMessage sms = SmsMessage.createFromPdu(pdu);
			// 短信的内容
			String message = sms.getMessageBody();
			Log.d("logo", "message     " + message);
			// 短息的手机号。。+86开头？
			String from = sms.getOriginatingAddress();
			Log.d("logo", "from     " + from);
			if (!TextUtils.isEmpty(from)) {
				String code = StringUtil.patternSmsCode(message);
				if (!TextUtils.isEmpty(code)) {
					for(SmsHandler smsHandler : mSmsListeners){
						smsHandler.onReceived(code);
					}
				}
			}
		}
	}
	
	public static abstract interface PhoneHandler {
		public abstract void onPhoned();
	}
	public static abstract interface SmsHandler {
		public abstract void onReceived(String sms);
	}
}